import React, { Component, PropTypes } from 'react';
import update from 'react/lib/update';
import PreviewTool from '../PreviewTool/index';
import { DropTarget, DragDropContext } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
import ItemTypes from '../PreviewTool/ItemTypes';
import {deleteItem,toggleIcon,moveItem} from '../../actions/index';
import {Dialog} from 'qnui';

const cardTarget = {

};

@DropTarget(ItemTypes.CARD, cardTarget, connect => ({
  connectDropTarget: connect.dropTarget()
}))
export default class MobileModel extends Component {
  static propTypes = {
    connectDropTarget: PropTypes.func.isRequired
  };
  constructor(props) {
    super(props);
    this.findCard = this.findCard.bind(this);
    this.toggleIcon = this.toggleIcon.bind(this);
    this.moveItem = this.moveItem.bind(this);
    this.removeItem = this.removeItem.bind(this);
  }

  findCard(id) {
    let cards = this.props.dataSource;
    const card = cards.filter(c => c.id === id)[0];
    return {
      card,
      index: cards.indexOf(card)
    };
  }
  toggleIcon(id,obj){
	  if(id>2){ //大于2 的模块才会出现上下挪动的icon
		const {card,index} = this.findCard(id);
		this.props.dispatch(toggleIcon(index,card))
	  }
  }
  moveItem(id,atIndex){
	  this.props.dispatch(moveItem(id,atIndex))
  }
  removeItem(index){
	  const data = this.props.dataSource;
	  if(data[index].isPrivate){
		  Dialog.alert({content:"这是模板专用组件，您不能删除它！"});
		  return;
	  }
	  this.props.dispatch(deleteItem(index,data[index].compId,data[0].pageId))
  }
  render() {
    const { canDrop, isOver,connectDropTarget } = this.props;
    let  cards  = this.props.dataSource;
	let dataLength = cards.length;
	cards.map(card => {
		  if(card.isDelete){
			  dataLength--;
		  }
	});
    return connectDropTarget(
	   <div className="phone-wrapper">
	    <div className="phone-rule-wrap"> <div className="phone-rule"></div> </div>
		<div className="phone-top"></div>
			{cards.map(card => {
			  if(!card.isDelete){
				  return (
					<PreviewTool 
						  key={card.id}
						  id={card.id}
						  fromData={card.fromData}
						  preview={card.preview}
						  showIcon={card.showIcon}
						  moveItem={this.moveItem}
						  removeItem={this.removeItem}
						  findCard={this.findCard}
						  dataLength={dataLength}
						  dispatch={this.props.dispatch} 
						  dataSource={this.props.dataSource}
						  toggleIcon={this.toggleIcon}
						  />
				  );
			  }
			})}
		<div className="phone-bottom"> <div id="ModuleNum" className="module-num">{cards.length-2}/20</div> </div>
      </div>
    );
  }
}